package concurrency;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by admin on 2017/1/21.
 */
public class TestCountDownLatch {

    static class WaitingTask implements Runnable{
        private CountDownLatch countDownLatch;
        WaitingTask(CountDownLatch latch){
            countDownLatch = latch;
        }

        @Override
        public void run() {
            try {
                countDownLatch.await();
                System.out.println("start waiting task");
            } catch (InterruptedException e) {
                System.out.print("waiting task interrupted");
            }
        }
    }

    static class PortionTask implements Runnable{
        private CountDownLatch countDownLatch;
        private int i;
        PortionTask(CountDownLatch latch, int i){
            this.countDownLatch = latch;
            this.i = i;
        }

        @Override
        public void run() {
            try {
                doWork();
                System.out.println("task "+i+"finished");
                countDownLatch.countDown();
            } catch (InterruptedException e) {
                System.out.print("portion task interrupted");
            }
        }

        private void doWork() throws InterruptedException {
            TimeUnit.SECONDS.sleep(2);
        }
    }

    public static void main(String[] arg0) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(100);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for(int i =0;i<10;i++){
            executorService.execute(new WaitingTask(latch));
        }
        for(int i = 0;i<100;i++){
            executorService.execute(new PortionTask(latch,i));
        }
        executorService.shutdown();
        TimeUnit.SECONDS.sleep(10);
    }
}
